import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
} from "axios";
import { message } from "antd";
import { showRotateVerify } from "../utils/verifyHelper";

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || "/api",
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 错误计数器（用于触发人机验证）
let errorCount = 0;
const ERROR_THRESHOLD = 3; // 连续错误3次触发验证

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error("请求错误:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    // 请求成功，重置错误计数
    errorCount = 0;

    const { data } = response;

    if (data.code === 200 || data.code === 0) {
      return data.data || data;
    }

    if (data.message) {
      message.error(data.message);
    }

    return Promise.reject(new Error(data.message || "请求失败"));
  },
  async (error: AxiosError) => {
    console.error("响应错误:", error);

    // 错误计数增加
    errorCount++;

    if (error.response) {
      const { status, data } = error.response;

      switch (status) {
        case 400:
          message.error((data as any)?.message || "请求参数错误");
          break;

        case 401:
          message.error("登录已过期，请重新登录");
          localStorage.removeItem("token");
          localStorage.removeItem("userInfo");
          window.location.href = "/login";
          break;

        case 403:
          message.error("没有权限访问");
          break;

        case 404:
          message.error("请求的资源不存在");
          break;

        case 429:
          // 请求频率过高，触发人机验证
          message.warning("请求过于频繁，请完成验证后继续");
          const verifyResult = await showRotateVerify(
            "请求频率限制",
            "检测到异常请求，请输入验证码后继续操作"
          );

          if (verifyResult) {
            // 验证成功，重置错误计数并重试请求
            errorCount = 0;
            return request(error.config as AxiosRequestConfig);
          } else {
            message.error("验证失败，请稍后重试");
          }
          break;

        case 500:
          message.error("服务器错误，请稍后重试");
          break;

        case 502:
          message.error("网关错误");
          break;

        case 503:
          message.error("服务不可用");
          break;

        default:
          message.error((data as any)?.message || "网络错误，请稍后重试");
      }

      // 连续错误达到阈值，触发人机验证
      if (errorCount >= ERROR_THRESHOLD && status !== 401) {
        message.warning("检测到异常操作，请完成验证");
        const verifyResult = await showRotateVerify(
          "安全验证",
          "检测到异常操作，请输入验证码后继续"
        );

        if (verifyResult) {
          // 验证成功，重置错误计数并重试请求
          errorCount = 0;
          return request(error.config as AxiosRequestConfig);
        } else {
          errorCount = 0;
          message.error("验证失败，请重新操作");
        }
      }
    } else if (error.request) {
      message.error("网络错误，请检查您的网络连接");
    } else {
      message.error(error.message || "请求失败");
    }

    return Promise.reject(error);
  }
);

// 封装GET请求
export const get = <T = any>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.get(url, { params, ...config });
};

// 封装POST请求
export const post = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.post(url, data, config);
};

// 封装PUT请求
export const put = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.put(url, data, config);
};

// 封装DELETE请求
export const del = <T = any>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.delete(url, { params, ...config });
};

// 封装PATCH请求
export const patch = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request.patch(url, data, config);
};

// 上传文件
export const upload = <T = any>(
  url: string,
  formData: FormData,
  onProgress?: (progressEvent: any) => void
): Promise<T> => {
  return request.post(url, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
    onUploadProgress: onProgress,
  });
};

export default request;
